package com.tjmc.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjmc.company.api.entity.CompanyInfoEntity;
import com.tjmc.company.mapper.CompanyInfoMapper;
import com.tjmc.company.service.CompanyInfoService;
import com.tjmc.recruit.common.core.constant.CommonConstants;
import com.tjmc.recruit.common.core.util.R;
import com.aliyun.tea.*;
import com.aliyun.teaopenapi.models.*;
import com.aliyun.dytnsapi20200217.models.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 企业信息服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CompanyInfoServiceImpl extends ServiceImpl<CompanyInfoMapper, CompanyInfoEntity> implements CompanyInfoService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<CompanyInfoEntity> registerCompany(CompanyInfoEntity companyInfo) {
        // 检查企业是否已存在
        CompanyInfoEntity existingCompany = baseMapper.selectById(companyInfo.getId());
        if (existingCompany != null) {
            return R.failed("企业已存在");
        }

        // 验证三要素并获取核验结果
        R<String> verificationResult = verifyCompanyThreeElements(companyInfo);
        if (verificationResult == null || verificationResult.getCode() != CommonConstants.SUCCESS) {
            return R.failed(verificationResult.getMsg());
        }
        companyInfo.setCertificationStatus("1");
        // 保存企业信息
        boolean save = save(companyInfo);
        if (!save) {
            return R.failed("注册失败");
        }

        return R.ok(companyInfo);
    }

    @Override
    public Page<CompanyInfoEntity> getCompanyPageByCategory(Page page, String category) {
        // 1. 根据类别查询企业列表
        return switch (category) {
            case "MEMBER" -> baseMapper.selectMemberCompanyPage(page);
            case "HIGH_SAL", "FAM" -> baseMapper.selectCompanyPageByCategory(page, category);
            default -> null;
        };
    }

    @Override
    public Page<CompanyInfoEntity> selectPageOrdered(Page page, LambdaQueryWrapper<CompanyInfoEntity> wrapper) {
        Page<Object> objectPage = new Page<>(page.getCurrent(), page.getSize());
        return baseMapper.selectPageOrdered(objectPage, wrapper);
    }

    @Override
    public Long countBeBrowsedNum(CompanyInfoEntity companyInfo) {
        return baseMapper.countBebrowsedNum(companyInfo.getId());
    }

    /**
     * 调用阿里云三要素核验接口验证企业信息，并返回详细核验结果
     *
     * @param companyInfo 企业信息实体
     * @return 核验结果 R<String>: 成功返回 "核验成功"，失败返回不匹配原因及具体内容。
     */
    private R<String> verifyCompanyThreeElements(CompanyInfoEntity companyInfo) {
        try {
            // 初始化阿里云 SDK 配置
            Config config = new Config()
                    .setAccessKeyId("LTAI5t8d4LSQPBJjhYUQmB5Z") // 替换为实际的 AccessKeyId
                    .setAccessKeySecret("8eBKgUeYbzV2CR3jf2jLO7vPqbpTL1") // 替换为实际的 AccessKeySecret
                    .setEndpoint("dytnsapi.aliyuncs.com");
            com.aliyun.dytnsapi20200217.Client client = new com.aliyun.dytnsapi20200217.Client(config);

            // 验证传入参数的完整性
            if (companyInfo.getCertificationNo() == null || companyInfo.getFullName() == null || companyInfo.getContactUserName() == null) {
                log.error("企业信息不完整: CertificationNo={}, FullName={}, ContactUserName={}",
                        companyInfo.getCertificationNo(), companyInfo.getFullName(), companyInfo.getContactUserName());
                throw new IllegalArgumentException("企业信息不完整");
            }

            // 创建请求对象并设置参数
            CompanyThreeElementsVerificationRequest request = new CompanyThreeElementsVerificationRequest()
                    .setEpCertNo(companyInfo.getCertificationNo())
                    .setEpCertName(companyInfo.getFullName())
                    .setLegalPersonCertName(companyInfo.getContactUserName())
                    .setAuthCode("Vg2w9F9XnT"); // 替换为实际的授权码

            // 调用阿里云接口
            CompanyThreeElementsVerificationResponse response =
                    client.companyThreeElementsVerificationWithOptions(request, new com.aliyun.teautil.models.RuntimeOptions());

            // 获取返回体
            CompanyThreeElementsVerificationResponseBody responseBody = response.getBody();
            CompanyThreeElementsVerificationResponseBody.CompanyThreeElementsVerificationResponseBodyData data = responseBody.getData();

            log.info("三要素核验返回结果: {}", data);

            if ("true".equalsIgnoreCase(data.getVerifyResult())) {
                log.info("企业三要素核验通过: {}", companyInfo.getFullName());
                return R.ok("核验成功");
            } else {
                StringBuilder detailedReason = new StringBuilder();

                // 根据 ReasonCode 提供更详细的原因描述
                int reasonCode = data.getReasonCode().intValue();
                switch (reasonCode) {
                    case 0:
                        detailedReason.append("核验一致，但未标记为通过；");
                        break;
                    case 1:
                        detailedReason.append("核验一致，但企业非正常营业；");
                        break;
                    case 2:
                        detailedReason.append("人企核验不一致；");
                        break;
                    case 3:
                        detailedReason.append("企业二要素核验不通过；");
                        break;
                    case 4:
                        detailedReason.append("查无企业信息；");
                        break;
                    case 5:
                        detailedReason.append("法人信息库中不存在；");
                        break;
                    default:
                        detailedReason.append("未知核验错误；");
                }

                // 不一致字段信息
                List<String> inconsistentData = data.getInconsistentData();
                if (inconsistentData != null && !inconsistentData.isEmpty()) {
                    for (String field : inconsistentData) {
                        if ("EpCertName".equalsIgnoreCase(field)) {
                            detailedReason.append("企业名称不一致（提供: ")
                                    .append(companyInfo.getFullName())
                                    .append("）；");
                        } else if ("EpCertNo".equalsIgnoreCase(field)) {
                            detailedReason.append("企业证件号不一致（提供: ")
                                    .append(companyInfo.getCertificationNo())
                                    .append("）；");
                        } else if ("CertName".equalsIgnoreCase(field)) {
                            detailedReason.append("企业法人姓名不一致（提供: ")
                                    .append(companyInfo.getContactUserName())
                                    .append("）；");
                        }
                    }
                }

                log.warn("企业三要素核验未通过: {}, 详细原因: {}", companyInfo.getFullName(), detailedReason);
                return R.failed("核验未通过: " + detailedReason);
            }
        } catch (TeaException teaException) {
            log.error("调用三要素核验接口时发生错误: {}", teaException.getMessage(), teaException);
            return R.failed("三要素核验接口调用失败: " + teaException.getMessage());
        } catch (Exception exception) {
            log.error("三要素核验失败", exception);
            return R.failed("三要素核验失败: " + exception.getMessage());
        }
    }
}
